package com.hyd.tweet.util;

import net.sf.jsr107cache.CacheException;
import net.sf.jsr107cache.CacheManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;

/**
 * 缓存。
 *
 * @author yiding.he
 */
@SuppressWarnings({"unchecked"})
public class Cache {

    static final Logger log = LoggerFactory.getLogger(Cache.class);

    public static final String CACHE_NAME = "HYDROGEN_TWEET_CACHE";
    
    public static final net.sf.jsr107cache.Cache CACHE = initCache();

    private static net.sf.jsr107cache.Cache initCache() {
        try {
            return CacheManager.getInstance().getCacheFactory().createCache(new HashMap());
        } catch (CacheException e) {
            throw new RuntimeException("初始化 CACHE 失败", e);
        }
    }

    public static void put(String key, Object value) {
        CACHE.put(key, value);
    }

    public static <T> T get(String key) {
        return (T) CACHE.get(key);
    }

    public static void remove(String key) {
        CACHE.remove(key);
    }

    public static int size() {
        return CACHE.size();
    }

    public static void clear() {
        CACHE.clear();
        log.info("缓存已清空。");
    }

    public static boolean containsKey(String key) {
        return CACHE.containsKey(key);
    }
}
